<?php

namespace App\Jobs;

use App\Models\TourOrder;
use Illuminate\Support\Facades\DB;

class TourTuanRefundJob extends Job
{
    protected $job_name ='TourTuanRefundJob';
    private $runtime = null;
    private $rows_per_loop =10;

    /**
     * 创建一个新的任务实例。
     *
     * @param $time 启动时间
     */
    public function __construct($time)
    {
        parent::__construct();
        $this->runtime = $time;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        //业务说明：定时给未成功团退款

        $this->logger->info('========start======');
        $this->logger->info('runtime:'.$this->runtime);
        //退款（卖家同意后的状态）
        $this->createCore();

        $this->logger->info('========end======');
    }

    private function createCore(){

        //团失败退款队列
        $this->logger->info('========退款======');

        $i =1;//批次
        $order_ids =null;

        while(true){

            $this->logger->info('【第'.$i.'批】');

            /* 团失败待退款的队列 */
            $order_ids = DB::table('tour_refund_queue')
                ->where('status',0)
                ->skip(0)->take($this->rows_per_loop)
                ->lists('order_id');

            /* 找到要退款的订单 */
            $orders = TourOrder::whereIn('order_id',$order_ids)
                ->select('order_id','buyer_id','order_amount','payment_code','tuan_id')
                ->get();

            $this->logger->info('总数:'.count($orders));

            if(count($orders)==0){
                break;
            }
            $order_id = array_column($orders->toArray(), 'order_id');
            
            $this->logger->info('执行: '.json_encode($order_id));

            DB::beginTransaction();

            try{

                foreach($orders as $order){

                    //创建线路退款单
                    //退款单创建
                    $tour_order_refund = [
                        'order_id'=>$order->order_id,
                        'applier'=>'0',
                        'apply_date'=>$this->runtime,
                        'apply_reason'=>'组团失败',
                        'receiver'=>'0',
                        'refund_status'=> TOUR_REFUND_REFUNDING,
                        'refund_remarks'=>'组团失败',
                        'last_time'=>$this->runtime,
                        'refund_fee'=>$order->order_amount,
                        'tuan_id'=>$order->tuan_id,
                        'added_by_batch'=>1
                    ];

                    $refund_id = DB::table('tour_order_refund')->insertGetId($tour_order_refund);

                    //操作日志
                    $tour_order_refund_log = [
                        'refund_id'=> $refund_id,
                        'operator'=>'0',
                        'refund_status'=> '组团失败自动退款',
                        'changed_status'=> '退款中',
                        'remark'=>'组团失败系统自动生成',
                        'log_time'=>$this->runtime,
                    ];

                    DB::table('tour_order_refund_log')->insert($tour_order_refund_log);

                    //更改订单状态
                    DB::table('tour_order')
                        ->where('order_id',$order->order_id)
                        ->update([
                            'status' => TOUR_ORDER_AGREE,//同意退款 等待退款
                        ]);

                    /* 操作记录 */
                    $order_log = [
                        'order_id'  => $order->order_id,
                        'operator'  => '0',
                        'order_status' => '组团中',
                        'changed_status' =>'组团失败退款' ,
                        'remark'    => '系统给组团失败订单退款',
                        'log_time'  => $this->runtime,
                    ];

                    DB::table('tour_order_log')->insert($order_log);

                    //组团失败退款队列
                    DB::table('tour_refund_queue')
                        ->where('order_id',$order->order_id)
                        ->delete();
                }

                DB::commit();

            } catch(\Exception $e){
                DB::rollback();
                $this->logger->info('error msg:'. $e->getMessage() . ' trace:'. $e->getTraceAsString());
            }
            if(count($order_ids)<$this->rows_per_loop){
                break;
            }

            $i++;

        }

    }

}
